const express = require('express');
const http = require('http');
const socketIo = require('socket.io');
const queueManager = require('./queue-manager');

// 创建Express应用
const app = express();
const server = http.createServer(app);

// 添加CORS中间件
app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  if (req.method === 'OPTIONS') {
    res.sendStatus(200);
  } else {
    next();
  }
});

// 创建Socket.IO实例
const io = socketIo(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});

// 中间件
app.use(express.json());

// API路由
app.get('/api/queue/status', (req, res) => {
    res.json(queueManager.getQueueStatus());
});

app.post('/api/queue/task', (req, res) => {
    const { task, callback } = req.body;
    const taskId = queueManager.enqueue(task, callback);
    res.json({ success: true, taskId });
});

// 添加历史记录API端点
app.get('/api/queue/history', (req, res) => {
    const history = queueManager.getHistory();
    res.json({ success: true, data: history });
});

// Socket.IO连接处理
io.on('connection', (socket) => {
    console.log('🔗 队列服务客户端已连接');
    
    // 监听任务添加请求
    socket.on('add-task', (data) => {
        console.log('📥 收到任务添加请求:', data);
        const taskId = queueManager.enqueue(data.task, (error, result) => {
            if (error) {
                socket.emit('task-error', { taskId: data.taskId, error: error.message });
            } else {
                socket.emit('task-complete', { taskId: data.taskId, result });
            }
        });
        
        socket.emit('task-added', { taskId });
    });
    
    // 获取队列状态
    socket.on('get-queue-status', () => {
        const status = queueManager.getQueueStatus();
        socket.emit('queue-status', status);
    });
    
    socket.on('disconnect', () => {
        console.log('🔌 队列服务客户端已断开');
    });
});

// 启动服务器
const PORT = 3003;
server.listen(PORT, () => {
    console.log(`🚀 队列服务运行在端口 ${PORT}`);
    console.log(`📡 API端点: http://localhost:${PORT}/api`);
    console.log(`🔌 Socket.IO: http://localhost:${PORT}`);
});

module.exports = { app, server };